<template>
  <div class="comment-container">
    <Row class="margin-top-10">
      <i-col span="24">
        <Card>
          <p class="title" slot="title">评论管理</p>
          <Form class="form">
            <span>根据书籍筛选&nbsp;&nbsp;</span>
            <Select
              v-model="bookid"
              filterable
              style="width:240px; margin-left: 10px"
              placeholder="请选择书籍"
              @on-change="bookChanged"
            >
              <Option v-for="item in allBooks" :value="item._id" :key="item._id">
                <span>{{ item.name }}</span>
                <span style="float:right;color:#ccc">{{ item.author }}</span>
              </Option>
            </Select>
          </Form>
          <Table :columns="columnsList" :data="tableData" :loading="loading"></Table>
          <Page
            class="pager"
            v-if="total > 0"
            :total="total"
            show-total
            show-elevator
            show-sizer
        :page-size="limit"
            @on-change="handlePageChange"
            @on-page-size-change="handlePageSizeChange"
          ></Page>
        </Card>
        <Modal
          class="comment-dialog"
          v-model="isShowModal"
          :title="modalTitle"
          :loading="modalLoading"
          @on-ok="handleModalConfrim"
          @on-cancel="handleModalCancel"
          width="600"
          :mask-closable="false"
        >
          <Form
            ref="modalForm"
            :model="modalData"
            :rules="modalRule"
            :label-width="100"
            label-position="left"
          >
            <FormItem prop="yuebi_num" label="回复的内容" :error="modalError.content">
              <i-input
                v-model="modalData.content"
                type="textarea"
                :autosize="{minRows: 3,maxRows: 5}"
                placeholder="请输入回复的内容"
              ></i-input>
            </FormItem>
            <FormItem prop="yuebi_num" label="是否发送模板消息给用户" :error="modalError.send_message">
              <i-switch v-model="modalData.send_message"></i-switch>
            </FormItem>
          </Form>
        </Modal>
      </i-col>
    </Row>
  </div>
</template>

<script>
import { oldHttp } from "@/utils/http";
import moment from "moment";

export default {
  name: "setting",
  data() {
    return {
      loading: true,
      bookid: "",
      tableData: [],
      allBooks: [],
      total: 0,
      page: 1,
      limit: 10,
      columnsList: [
        {
          title: "序号",
          key: "index",
          width: 80,
          align: "center"
        },
        {
          title: "评论书籍",
          align: "center",
          render: (h, params) => {
            return h("span", [params.row.bookid.name]);
          }
        },
        {
          title: "用户",
          align: "center",
          render: (h, params) => {
            return h("span", [params.row.userid.username]);
          }
        },
        {
          title: "内容",
          align: "center",
          width: 300,
          render: (h, params) => {
            return h("span", [params.row.content]);
          }
        },
        {
          title: "点赞数",
          align: "center",
          key: "type",
          width: 80,
          render: (h, params) => {
            return h("span", [h("b", params.row.like_persons.length)]);
          }
        },
        {
          title: "创建时间",
          align: "center",
          key: "create_time",
          render: (h, params) => {
            return h(
              "span",
              moment(params.row.create_time).format("YYYY/MM/DD HH:MM:SS")
            );
          }
        },
        {
          title: "操作",
          align: "center",
          width: 240,
          key: "handle",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  class: "change-btn",
                  props: {
                    type: "primary"
                  },
                  on: {
                    click: () => {
                      this.modalData = {
                        commentid: params.row._id,
                        bookid: params.row.bookid._id,
                        content: "",
                        send_message: true
                      };
                      this.isShowModal = true;
                      this.modalTitle =
                        "系统管理员回复 " + params.row.userid.username;
                    }
                  }
                },
                "回复"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error"
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "温馨提示",
                        content: "确定要删除此评论及其子评论？",
                        onOk: () => {
                          oldHttp
                            .delete(
                              "/api/admin/comment",
                              {
                                commentid: params.row._id,
                                bookid: params.row.bookid._id
                              },
                              "删除评论"
                            )
                            .then(res => {
                              if (res.ok) {
                                // 更新tableData
                                this.isShowModal = false;
                                this.$Message.success("删除评论成功");
                                this.getData();
                              }
                            });
                        },
                        onCancel: () => {}
                      });
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      isShowModal: false, // 控制modal的显隐
      modalLoading: true, // 点击modal确定按钮是否显示loading
      modalTitle: "", // modal标题
      currentId: "", // 当前正在修改的评论Id
      modalData: {
        content: "",
        send_message: ""
      },
      modalRule: {
        content: [
          {
            required: true,
            type: "number",
            message: "请输入回复的内容",
            trigger: "blur"
          }
        ],
        send_message: []
      },
      modalError: {} // modal错误提示信息
    };
  },
  methods: {
    // get all books
    getAllBooks() {
      let self = this;
      oldHttp
        .get("/api/admin/book/sign_good", {}, "获取全部书籍列表")
        .then(res => {
          if (res && res.ok) {
            self.allBooks = res.list;
          }
        });
    },
    bookChanged(value) {
      this.page = 1;
      this.limit = 10;
      this.getData();
    },
    getData() {
      let self = this;
      self.loading = true;
      oldHttp
        .get(
          "/api/admin/comment",
          { page: self.page, limit: self.limit, bookid: self.bookid },
          "获取评论列表"
        )
        .then(res => {
          self.loading = false;
          if (res.ok) {
            self.tableData = res.list.map((item, index) => {
              item.index = (self.page - 1) * self.limit + index + 1;
              return item;
            });
            self.total = res.total;
          }
        });
    },
    handleModalConfrim() {
      let self = this;
      // 合法性校验
      self.$refs["modalForm"].validate(valid => {
        if (valid) {
          oldHttp
            .post("/api/admin/comment/reply", this.modalData, "新增评论")
            .then(res => {
              self.modalLoading = false;
              // 避免校验完直接关闭弹窗
              self.$nextTick(() => {
                self.modalLoading = true;
              });
              if (res.ok) {
                self.isShowModal = false;
                self.$Message.success("新增评论成功");
              }
            })
            .catch(err => {
              self.modalLoading = false;
              self.$nextTick(() => {
                self.modalLoading = true;
              });
            });
        }
      });
    },
    handleModalCancel() {
      this.$refs["modalForm"].resetFields();
    },
    // 点击分页
    handlePageChange(val) {
      this.page = val;
      this.getData();
    },
    handlePageSizeChange(size) {
      this.limit = size;
      this.getData();
    }
  },
  created() {
    this.getData();
    this.getAllBooks();
  }
};
</script>

<style lang="scss">
.comment-container .title {
  height: 32px;
  line-height: 32px;
}
.comment-container .form {
  margin-bottom: 20px;
  position: relative;
  margin-top: 0;
}
.comment-container .add-icon {
  float: right;
}
.comment-container .overflow-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.comment-container .ivu-tooltip-inner {
  max-width: inherit;
}
.comment-container .change-btn {
  margin-right: 15px;
}
.comment-container .modal-container {
  width: 600px;
  position: absolute;
  left: 50%;
  top: 0;
  margin-left: -300px;
}
.comment-dialog textarea.ivu-i-input {
  font-size: 12px !important;
}
.comment-container .pager {
  text-align: right;
  margin-top: 30px;
}
.comment-container .book-img {
  width: 50px;
  height: 80px;
  float: left;
  margin-right: 10px;
}
.comment-container .book-detail > p {
  text-align: left;
  padding-right: 10px;
}
</style>
